<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'

import {
  useMessage,
  NButton, NForm, NFormItem, NInput, NInputNumber, NPopconfirm, NTreeSelect, NTag, NSwitch, NFlex,
  NAvatar, NSelect, NImage
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import TheIcon from '@/components/icon/TheIcon.vue'
import { getToken } from '@/utils'
import { renderIcon } from '@/utils'
import { useCRUD } from '@/composables'
// import { loginTypeMap, loginTypeOptions } from '@/constant/data'
import api from '@/api'

defineOptions({ name: '直播间管理' })

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const base_path = import.meta.env.VITE_BASE

const {
  modalVisible,
  modalTitle,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '直播间管理',
  initForm: {},
  doCreate: api.createLives,
  doUpdate: api.updateLives,
  doDelete: api.deleteLives,
  refresh: () => $table.value?.handlerefresh(),
})
const isDisabled = ref(false)
const data = reactive({
  attributeOption: [],
  contact_goods_options:[],
  uploadAction: base_path + 'api/marketing/lives/file',
  token: getToken(),
});


onMounted(() => {
  $table.value?.handleSearch()
  api.getallgoods().then((res) => (data.contact_goods_options = res.data))
})
//封面图
const message = useMessage();
const customRequestMethod1 = (options) => {
  const { file } = options.file;
  const formData = new FormData();
  formData.append('file', file);
  fetch(data.uploadAction, {
    method: 'POST',
    headers: options.headers,
    body: formData,
  })
      .then((response) => response.json())
      .then((data) => {
        if (data.code === 200) {
          modalForm.value.cover = data.data.url
          message.success('封面图上传成功');
          options.onProgress(data);
        } else {
          message.error(data.msg);
        }
      })
}
const customRequestMethod2 = (options) => {
  const { file } = options.file;
  const formData = new FormData();
  formData.append('file', file);
  fetch(data.uploadAction, {
    method: 'POST',
    headers: options.headers,
    body: formData,
  })
      .then((response) => response.json())
      .then((data) => {
        if (data.code === 200) {
          modalForm.value.button_image = data.data.url
          message.success('按钮图上传成功');
          options.onProgress(data);
        } else {
          message.error(data.msg);
        }
      })
}
const customRequestMethod3 = (options) => {
  console.log(options, 'options');
  const { file } = options.file;
  const formData = new FormData();
  formData.append('file', file);
  fetch(data.uploadAction, {
    method: 'POST',
    headers: options.headers,
    body: formData,
  })
      .then((response) => response.json())
      .then((data) => {
        if (data.code === 200) {
          modalForm.value.share_image = data.data.url
          message.success('分享图上传成功');
          options.onProgress(data);
        } else {
          message.error(data.msg);
        }
      })
}

async function addDepts() {
  isDisabled.value = false
  handleAdd()
}

const columns = [
  {
    title: 'ID',
    key: 'id',
    width: 100,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '直播间名称',
    key: 'name',
    width: 'auto',
    align: 'center',
    ellipsis: { tooltip: true },
    fixed: 'left',
  },
  {
    title: '封面',
    key: 'cover',
    width:'auto',
    align: 'center',
    ellipsis: { tooltip: true },
    render(row) {
      return h(NFlex, {},
          [h(NAvatar, {
            src: row.cover,
            size: "small",
          })]
      )

    },
  },
  {
    title: '按钮图',
    key: 'button_image',
    width: 'auto',
    align: 'center',
    ellipsis: { tooltip: true },
    render(row) {
      return h(NFlex, {},
          [h(NAvatar, {
            src: row.button_image,
            size: "small",
          })]
      )

    },
  },
  {
    title: '分享图',
    key: 'share_image',
    width: 'auto',
    align: 'center',
    ellipsis: { tooltip: true },
    render(row) {
      return h(NFlex, {},
          [h(NAvatar, {
            src: row.share_image,
            size: "small",
          })]
      )

    },
  },
  {
    title: '直播开始时间',
    key: 'begin_time',
    align: 'center',
    width: 'auto',
    ellipsis: { tooltip: true },
  },{
    title: '关联商品',
    key: 'goods_ids',
    align: 'center',
    width: 'auto',
    ellipsis: { tooltip: true },
    render(row) {
      return  JSON.stringify(row.goods_ids)

    },
  },
  {
    title: '操作',
    key: 'actions',
    width: 'auto',
    align: 'center',
    fixed: 'right',
    render(row) {
      return [
        withDirectives(
            h(
                NButton,
                {
                  size: 'small',
                  type: 'primary',
                  style: 'margin-right: 8px;',
                  onClick: () => {
                    console.log('row', row.parent_id)
                    if (row.parent_id === 0) {
                      isDisabled.value = true
                    } else {
                      isDisabled.value = false
                    }
                    handleEdit(row)
                  },
                },
                {
                  default: () => '编辑',
                  icon: renderIcon('material-symbols:edit', { size: 16 }),
                }
            ),
            [[vPermission, 'post/api/content/category/update']]
        ),
        h(
            NPopconfirm,
            {
              onPositiveClick: () => handleDelete({ data_id: row.id }, false),
              onNegativeClick: () => { },
            },
            {
              trigger: () =>
                  withDirectives(
                      h(
                          NButton,
                          {
                            size: 'small',
                            type: 'error',
                          },
                          {
                            default: () => '删除',
                            icon: renderIcon('material-symbols:delete-outline', { size: 16 }),
                          }
                      ),
                      [[vPermission, 'delete/api/content/category/delete']]
                  ),
              default: () => h('div', {}, '确定删除该分类吗?'),
            }
        ),
      ]
    },
  },
]

//格式化关联商品选中
const renderLabel = function({ option }) {
  return h(
      "div",
      {
        style: {
          display: "flex",
          margin: "6px 0"
        }
      },
      {
        default: () => [
          h(NAvatar, {
            round: true,
            src: option.cover,
            size: "small",
            fallbackSrc: "https://07akioni.oss-cn-beijing.aliyuncs.com/07akioni.jpeg"
          }),
          h(
              "div",
              {
                style: {
                  display: "flex",
                  marginLeft: "6px",
                  alignSelf: "center"
                }
              },
              { default: () => option.label }
          )
        ]
      }
  );
};

const validateAddUser = {
    name: [
        {
            required: true,
            message: '请输入名称',
            trigger: ['input', 'blur', 'change'],
        },
    ],
}
</script>

<template>
  <!-- 业务页面 -->
  <CommonPage show-footer title="直播间列表">
    <template #action>
      <div>
        <NButton v-permission="'post/api/content/category/create'" class="float-right mr-15" type="primary"
                 @click="addDepts">
          <TheIcon icon="material-symbols:add" :size="18" class="mr-5" />新建直播间
        </NButton>
      </div>
    </template>
    <!-- 表格 -->
    <CrudTable ref="$table" v-model:query-items="queryItems" :columns="columns" :get-data="api.getLives"
               :scroll-x="1100">
      <template #queryBar>
        <QueryBarItem label="直播间名称" :label-width="80">
          <NInput v-model:value="queryItems.name" clearable type="text" placeholder="请输入直播间名称"
                  @keypress.enter="$table?.handleSearch()" />
        </QueryBarItem>
      </template>
    </CrudTable>

    <!-- 新增/编辑 弹窗 -->
    <CrudModal v-model:visible="modalVisible" :title="modalTitle" :loading="modalLoading" @save="handleSave"
               style="width: 1000px !important;">
      <NForm ref="modalFormRef" label-placement="left" label-align="left" :label-width="80" :model="modalForm"
             :rules="validateAddUser">
        <NFlex justify="space-between">
          <n-card content-style="padding: 0;">
            <n-tabs type="line" animated size="large" :tabs-padding="20" pane-style="padding: 20px;">
              <n-tab-pane name="基础信息">
                <NFormItem label="直播名称" path="name" style="width: 100%;">
                  <NInput v-model:value="modalForm.name" clearable placeholder="请输入品牌名称" />
                </NFormItem>
                <NFormItem label="直播封面" path="cover" style="width:100%">
                  <NImage v-if="modalForm.cover" width="60" style="border-radius: 5px;margin-right: 15px;"
                          :src="modalForm.cover"></NImage>
                  <NUpload :action="data.uploadAction" :headers="{ token: data.token }" :max="1"
                           :show-file-list=false :custom-request="customRequestMethod1" list-type="image">
                    <NButton>上传</NButton>
                  </NUpload>
                </NFormItem>
                <NFormItem label="直播按钮" path="logo_image" style="width:100%">
                  <NImage v-if="modalForm.button_image" width="60" style="border-radius: 5px;margin-right: 15px;"
                          :src="modalForm.button_image"></NImage>
                  <NUpload :action="data.uploadAction" :headers="{ token: data.token }" :max="1"
                           :show-file-list=false :custom-request="customRequestMethod2" list-type="image">
                    <NButton>上传</NButton>
                  </NUpload>
                </NFormItem>
                <NFormItem label="分享图" path="share_image" style="width:100%">
                  <NImage v-if="modalForm.share_image" width="60" style="border-radius: 5px;margin-right: 15px;"
                          :src="modalForm.share_image"></NImage>
                  <NUpload :action="data.uploadAction" :headers="{ token: data.token }" :max="1"
                           :show-file-list=false :custom-request="customRequestMethod3" list-type="image">
                    <NButton>上传</NButton>
                  </NUpload>
                </NFormItem>
                <NFormItem label="开始时间" path="begin_time" style="width: 100%;">
                  <n-date-picker
                      v-model:formatted-value="modalForm.begin_time"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      type="datetime"
                      placeholder="选择开始时间"
                      clearable
                  />
                </NFormItem>
              </n-tab-pane>
              <n-tab-pane name="关联商品">
                <NFormItem label="关联商品" path="goods_ids">
                  <n-transfer
                      v-model:value="modalForm.goods_ids"
                      :options="data.contact_goods_options"
                      :render-target-label="renderLabel"
                      style="width: 1200px"
                      source-filterable
                  />
                </NFormItem>
              </n-tab-pane>
            </n-tabs>
          </n-card>


        </NFlex>
      </NForm>
    </CrudModal>
  </CommonPage>
</template>
